<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <!-- STYLESHEETS -->
    <!--[if lt IE 9]>
    <script src="../../js/flot/excanvas.min.js"></script>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script><![endif]-->
    <link rel="stylesheet" type="text/css" href="../../css/cloud-admin.css">
    <link rel="stylesheet" type="text/css" href="../../css/themes/default.css" id="skin-switcher">
    <link rel="stylesheet" type="text/css" href="../../css/responsive.css">

    <link href="../../font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <!-- file-input -->
    <link rel="stylesheet" type="text/css" href="../../js/file-input/fileinput.css"/>
    <!-- SELECT2 -->
    <link rel="stylesheet" type="text/css" href="../../js/select2/select2.min.css"/>
    <!-- UNIFORM -->
    <link rel="stylesheet" type="text/css" href="../../js/uniform/css/uniform.default.min.css"/>
    <!-- datatable -->
    <link rel="stylesheet" href="../../js/datatables/datatable.css">
    <!-- WIZARD -->
    <link rel="stylesheet" type="text/css" href="../../js/bootstrap-wizard/wizard.css"/>
    <link rel="stylesheet" href="../../js/datepicker/datepicker.css">
    <!-- FONTS
<link href='http://fonts.useso.com/css?family=Open+Sans:300,400,600,700' rel='stylesheet' type='text/css'>
--> <!-- file-input -->
    <link rel="stylesheet" type="text/css" href="../../js/file-input/fileinput.css"/>
    <!-- JQUERY -->
    <script src="../../js/jquery/jquery-2.0.3.min.js"></script>
    <script src="../../js/common.js"></script>

    <style>

        .left {
            float: left;
            width: 45%;
            height: 400px;
        }

        .right {
            float: left;
            width: 55%;
            height: 400px;
            position: relative;
        }

        .floatDiv {
            width: 160px;
            height: 150px;
            border: 1px dotted blue;
            padding: 10px;
            position: relative;
            left: 65%;
            top: -45%;
        }
    </style>
</head>

<body>
<header class="navbar clearfix" id="header">
</header>
<input id="p_code" type="hidden" name="p_code" value="" /> 
<!-- PAGE -->
<section id="page">
    <!-- SIDEBAR -->
    <div id="sidebar" class="sidebar">
        <div class="sidebar-menu nav-collapse">

            <!-- SIDEBAR MENU -->
            <ul>

            </ul>
            <!-- /SIDEBAR MENU -->
        </div>

    </div>
    <!-- /SIDEBAR -->
    <div id="main-content">

        <div class="container">
			
            <div class="row">
                <div id="content" class="col-lg-12" >
                    <!-- PAGE HEADER-->
				<div class="row">
								<div class="col-sm-12">
									<div class="page-header">
										<!-- STYLER -->

										<!-- /STYLER -->
										<!-- BREADCRUMBS -->
										<ul class="breadcrumb">
											<li>
												<i class="fa fa-home"></i>
												<a href="index.html">首页</a>
											</li>
											<li>
												<a href="#">商品管理</a>
											</li>
											<li>维护商品</li>
										</ul>
										<!-- /BREADCRUMBS -->

									</div>
								</div>
							</div>
                <form id="main">
				<div class="box-body">
					<div class="form-group  mrg-bt10">
						<label class="control-label col-md-2 " style="width:100px"><span class="required">*</span>供应商：</label>
						 <div class="col-md-3 inline">
							<select id="supplier_select" name="supplierId" class="col-md-10 select2-offscreen">
							</select>
							<span class="error-span"></span>
						</div>
						<label class="control-label col-md-2 " style="width:120px"><span class="required">*</span>合同编号：</label>
						 <div class="col-md-2 inline">
							<select id="contract_select" name="contractIda" style="min-width:120px;">
							</select>
							<span class="error-span"></span>
						</div>
						<label class="control-label col-md-2 " style="width:140px"><span class="required">*</span>预计到货时间：</label>
						 <div class="col-md-2 inline">
							<div class="col-md-2">
								<input class="Wdate" style="height:34px" type="text" id="d4311" name="preSaleDate" onfocus="WdatePicker({maxDate:'#F{\'2030-10-01\'}',dateFmt:'yyyy-MM-dd'})">
							</div>
							<span class="error-span"></span>
						</div>
					</div>
		
					
				</div>


                    <div class="detail_list ">

                        <div style="float:left; margin-left:5px; margin-right: 10px" class="addnewimg" id="f_span">
												
							<!--
                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0"
                                 aria-valuemax="100" style="margin-bottom: 0px; margin-top: 10px; display: none;">
                                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                            </div>
							-->
							 <a href="javaScript:;" class="btn btn-success downloadBtn">
								模板下载
							</a>
							<span class="btn btn-success btn-file" id="fir">
								<span id="two">导入进货明细</span>
									<input name="uploadFile" upload-file="imageUrlProduct"
										   type="file">
							</span>
							<span style="color:red;">(请导入全部进货明细)</span>
                        </div>
						<div style="float:right; margin-right: 20px;margin-bottom:5px;" class="addnewimg" id="f_span">
							<a href="javaScript:;" class="btn btn-success saveBtn">
								<i class="fa  fa-plus-square-o"></i> 生成进货单
							</a>
						</div>

                       

                        <div class="box border primary" style="margin-top: 15px">
                            <div class="box-title">
                                <h4><i class="fa fa-table"></i>总件数：<span id="total_number"></span>，总金额：<span id="total_price"></span> </h4>
                            </div>
                            <div class="box-body" style="min-height: 200px" id="box_table">
                                <table id="importData" cellpadding="0" cellspacing="0" border="0"
                                       class="datatable table table-striped table-bordered table-hover">

                                </table>
                            </div>
                        </div>


                    </div>
                  </form>
                </div>
                <!-- /CONTENT-->
            </div>
        </div>
    </div>
</section>
<!-- JQUERY -->
<script src="../../js/jquery/jquery-2.0.3.min.js"></script>
<script src="../../js/common.js"></script>
<!-- JQUERY UI-->
<script src="../../js/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
<!-- BOOTSTRAP -->
<script src="../../bootstrap-dist/js/bootstrap.min.js"></script>
<!-- SLIMSCROLL -->
<script type="text/javascript" src="../../js/jQuery-slimScroll-1.3.0/jquery.slimscroll.min.js"></script>
<script type="text/javascript" src="../../js/jQuery-slimScroll-1.3.0/slimScrollHorizontal.min.js"></script>
<!-- BLOCK UI -->
<script type="text/javascript" src="../../js/jQuery-BlockUI/jquery.blockUI.min.js"></script>
<!--bootbox-->
<script type="text/javascript" src="../../js/bootbox/bootbox.min.js"></script>
<!-- AUTOSIZE -->
<script type="text/javascript" src="../../js/autosize/jquery.autosize.min.js"></script>
<!-- spinner -->
<script src="../../js/spinner/spin.js"></script>
<!-- bootstrap-fileupload -->
<script type="text/javascript" src="../../js/jquery-upload/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="../../js/jquery-upload/js/jquery.fileupload.min.js"></script>
<script type="text/javascript" src="../../js/jquery-upload/js/jquery.fileupload-process.min.js"></script>
<script type="text/javascript" src="../../js/jquery-upload/js/jquery.fileupload-validate.min.js"></script>

<!-- INPUT MASK -->
<script type="text/javascript" src="../../js/bootstrap-inputmask/bootstrap-inputmask.min.js"></script>

<!-- SELECT2 -->
<script type="text/javascript" src="../../js/select2/select2.min.js"></script>
<!-- UNIFORM -->
<script type="text/javascript" src="../../js/uniform/jquery.uniform.min.js"></script>
<!-- WIZARD -->
<script src="../../js/bootstrap-wizard/jquery.bootstrap.wizard.min.js"></script>
<!-- WIZARD -->
<script src="../../js/jquery-validate/jquery.validate.min.js"></script>
<script src="../../js/jquery-validate/additional-methods.min.js"></script>
<script src="../../js/bootstrap-wizard/form-wizard.js"></script>
<script language="javascript" type="text/javascript" src="../../js/My97DatePicker/WdatePicker.js"></script>
<!-- NESTABLE LISTS -->
<script type="text/javascript" src="../../js/nestable/jquery.nestable.min.js"></script>
<!-- COOKIE -->
<script type="text/javascript" src="../../js/jQuery-Cookie/jquery.cookie.min.js"></script>
<!-- CUSTOM SCRIPT -->
<script src="../../js/script.js"></script>

<script src="../../js/Sortable.min.js"></script>

<!-- DATA TABLES -->
<script type="text/javascript" src="../../js/datatables/bootstrap-select.js"></script>
<script type="text/javascript" src="../../js/datatables/datatable.js"></script>
<script type="text/javascript" src="../../js/datatables/datatable-bootstrap.js"></script>
<script type="text/javascript" src="../../js/datatables/datatable-tabletools.js"></script>
<script type="text/javascript" src="../../js/datatables/fnAddTr.js"></script>
<script>
    var datetables = null;
    var count = 0;
	var purchaseid = $.getUrlParam("pid");
	var supplierid = $.getUrlParam("sid");
	var contractid = $.getUrlParam("ccode");
    var init = function () {
        App.init();
		//绑定供应商、合同编号下拉框
		selectBind();
		//获取进货单详情
		getPurchaseInfo();
		
		$("[upload-file=imageUrlProduct]").click(function () {
            var ctext = $("#contract_select").find("option:selected").text();
			if(ctext =="")
			{
				$.alert("请选择合同编号");
				return false;
			}
			else
			{
				return true;
			}
        });
		//文件上传前触发事件
		var contractId = "";
		$("[upload-file=imageUrlProduct]").bind('fileuploadsubmit', function (e, data) {
			var cid = $("#contract_select").find("option:selected").attr("contractid");
			data.formData = { contractId: cid };  //如果需要额外添加参数可以在这里添加
		});
        //导入模板
        $("[upload-file=imageUrlProduct]").fileupload({
            url: App.getContextPath() + "admin/purchase/readTemplate.do",
            dataType: 'json',
            acceptFileTypes: /(\.|\/)(xlsx)$/i,
            iframe: true,
            start: function (e) {
                $('.progress').fadeIn(300);
                return true;
            },
            autoUpload: true,
            done: function (e, data) {
                if (data.result.type == 'error') {
                    $.alert("导入的数据有问题");
                } else {
					if(purchaseid !="" ){
						$("#box_table").html("");
						var str = " <table id='importData' cellpadding='0' cellspacing='0' border='0' class='datatable table table-striped table-bordered table-hover'></table>";
						$("#box_table").append(str);
					}
					initDateTable(data.result.extra);
					
					var totalnumber = 0;
					var totalprice = 0;
					for(var i=0;i<data.result.extra.length;i++)
					{
						totalnumber +=data.result.extra[i].quantity;
						totalprice  += data.result.extra[i].quantity * data.result.extra[i].price;
					}
					
					$("#total_number").html(totalnumber);
					$("#total_price").html(totalprice.toFixed(4));
                }

            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('.progress .progress-bar').css('width', progress + '%');
            }
        }).on('fileuploaddone', function (e, data) {
            $(".progress").fadeOut(300);

        });

        //下载
        $(".downloadBtn").click(function () {
            location.href = App.getContextPath() + "admin/file/downloadTemplate.do?template=Purchase";
        });

		//保存
        $(".saveBtn").click(function () {
          
		   var purinfo = {};
		   if(purchaseid !="")
		   {
				purinfo.id=$("#p_code").val();
				purinfo.purchaseCode=purchaseid;
		   }
		   purinfo.supplierId = $("#supplier_select").find("option:selected").val();
		   purinfo.contractCode = $("#contract_select").find("option:selected").text();
		   purinfo.preArriveDate = $("input[name=preSaleDate]").val();
		   if(purinfo.supplierId =="undefined" || purinfo.supplierId<1)
		   {
				$.alert("请选择供应商");
				return;
		   }
		   if(purinfo.contractCode =="undefined" || purinfo.contractCode == "")
		   {
				$.alert("请选择合同编号");
				return;
		   }
		   if(purinfo.preArriveDate =="undefined" || purinfo.preArriveDate == "")
		   {
				$.alert("请选择预计到货时间");
				return;
		   }
		   purinfo.purchaseDetail = [];
		   var is_check = true;
		   $("#importData tbody tr").each(function(){
				var sku = {};
				sku.skuCode=$(this).find("td:eq(0)").html();
				sku.quantity=$(this).find("td:eq(4)").html();
				purinfo.purchaseDetail.push(sku);
				var remark = $(this).find("td:eq(6)").html();
				if(remark != "")
				{
					is_check = false;
					return;
				}
			});	

			if(!is_check)			
			{
				$.alert("进货明细数据有问题");
				return;
			}
		   if(purinfo.purchaseDetail ==null || purinfo.purchaseDetail.length <1)
		   {
				$.alert("请导入进货明细");
				return;
		   }		
		  
		
		   //提交数据
		   $.ajax({
				type: "post",
				url: App.getContextPath() + "admin/purchase/savePurchase.do",
				data:$.param({purchase:JSON.stringify(purinfo)}),
				async: true,
				success: function(result) {
					if(result.type=="error"){
						$.alert(result.extra);}
					else{
						$.alert("保存成功");
						
						location.href="index.html";
						}	
					}					
			});


        });

    }
	
	var getPurchaseInfo = function(){
		if(purchaseid == null || purchaseid =="")
		{
			return;
		}
		else
		{
			$.ajax({
					type: "post",
					url: App.getContextPath()+"admin/purchase/getPurchaseById.do",
					async: true,
					data: {code:purchaseid},
					success: function(result) {
						initDateTable(result.data[0].purchaseDetail);
						$("#p_code").val(result.data[0].id);

						$("input[name=preSaleDate]").val($.getLocalDate(result.data[0].preArriveDate));
						
						var totalnumber = 0;
						var totalprice = 0;
						for(var i=0;i<result.data[0].purchaseDetail.length;i++)
						{
							totalnumber +=result.data[0].purchaseDetail[i].quantity;
							totalprice  += result.data[0].purchaseDetail[i].quantity * result.data[0].purchaseDetail[i].price;
						}
						
						$("#total_number").html(totalnumber);
						$("#total_price").html(format_thousands(totalprice));
					}
				});
		}
	}
	
	var selectBind = function(){
		$.ajax({
			type: "post",
			url: App.getContextPath()+"admin/supplier/searchSupplierList.do",
			async: false,			
			success: function(result) {
				if(result!=null)
				{ 	
					var option="";
					$.each(result,function(index,item){								
						 option+="<option value='"+item.id+"'>"+item.supplierName+"</option>";
					});
					if(supplierid>0)
					{
						$("#supplier_select").empty().append(option).select2();
						$("#supplier_select").select2("val",parseInt(supplierid));
					}
					else
					{
						$("#supplier_select").empty().append(option).select2();
					}
					
					$.ajax({
						type: "post",
						url: App.getContextPath()+"admin/contract/findContractListBySupplier.do?supplierId=" + $("#supplier_select").select2("val"),
						async: false,			
						success: function(result) {
							if(result!=null)
							{ 	
								var option="";
								$.each(result,function(index,item){								
									 option+="<option value='"+item.contractCode+"' contractid='"+item.id+"'>"+item.contractCode+"</option>";
								});
								if(contractid != null && contractid != "undefined" && contractid != "")
								{
									$("#contract_select").empty().append(option).select2();
									$("#contract_select").select2("val",contractid);
								}
								else
								{
									$("#contract_select").empty().append(option).select2();
								}
								
								
							}
							
						}
					});
				}
			}
		});
				

	}
	
	 $("#supplier_select").change(function () {
			var sid = $(this).val();
			$.ajax({
				type: "post",
				url: App.getContextPath()+"admin/contract/findContractListBySupplier.do?supplierId=" + sid,
				async: true,			
				success: function(result) {
					if(result!=null)
					{ 	
						var option="";
						$.each(result,function(index,item){								
							 option+="<option value='"+item.contractCode+"' contractid='"+item.id+"'>"+item.contractCode+"</option>";
						});
						$("#contract_select").empty().append(option).select2();
						
						
						
					}
					
				}
			});
					
        });

    var initDateTable = function (data) {
        var dtSetting = {
            "serverSide": false,
            "bFilter": false,// 去掉搜索框
            "sScrollX": "100%",
            "sScrollXInner": "100%",
            "bSort": false,
            "paging": false,
            "data": data,
            "info": false,
            "drawCallback": function (settings) {
                var api = this.api();
                var datas = api.rows().data();
                var amount = 0;
                var goodsAccount = 0;
                for (var i = 0; i < datas.length; i++) {
                    var e = datas[i];
                    amount += e.price * e.quantity;
                    goodsAccount += e.quantity;
                }
                $("[name=contractPrice]").val(amount);
                $("[name=quantity]").val(goodsAccount);
            },
            "aoColumns": [{
                "mDataProp": "skuCode",
                "sTitle": "SKU/物料编码",
                "width": "6%"
            }, {
                "mDataProp": "productName",
                "sTitle": "商品/物料名称",
                "width": "10%"
            }, {
                "mDataProp": "color",
                "sTitle": "颜色",
                "width": "6%"
            }, {
                "mDataProp": "sizeName",
                "sTitle": "规格/大小",
                "width": "6%"
            }, {
                "mDataProp": "quantity",
                "sTitle": "数量",
                "width": "6%"
            }, {
                "mDataProp": "price",
                "sTitle": "单价",
                "width": "6%"
            }, {
                "mDataProp": "remark",
                "sTitle": "提示",
                "width": "10%",
                "render": function (data, type, row) {
					if(row.remark != null && row.remark !="")
						return "<span style='color:red'>" + row.remark + "</span>";
					else
						return "";
                }
            }]
        };
        datetables = $("#importData").dataTable(dtSetting);

    }



    $(function () {
        $("#header").load("../head.html");
        init();
    });
</script>

<!-- /JAVASCRIPTS -->
</body>

</html>